<?php

namespace app\admin\controller;
use app\admin\model\BydAgreement;
use app\admin\model\Bydletter;
use app\common\controller\News;
use think\db;
require EXTEND_PATH.'phpoffice/src/phpword/Shared/ZipArchive.php';
require EXTEND_PATH.'phpoffice/src/phpword/TemplateProcessor.php';
require EXTEND_PATH.'phpoffice/src/phpword/Settings.php';
use app\common\controller\Backend;

/**
 * 设计师
 *
 * @icon fa fa-circle-o
 */
class BydDesigner extends Backend
{
    
    /**
     * BydDesigner模型对象
     * @var \app\admin\model\BydDesigner
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\BydDesigner;
        $this->view->assign("stateList", $this->model->getStateList());
    }

    public function import()
    {
        parent::import();
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['byduser'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {


            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $user=\app\admin\model\BydUser::find($params['user_id']);
                if($params['state']==1){
                    $useragfind=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->order('id desc')->find();
                    if(!empty($useragfind)){
                        $agment=BydAgreement::where('id',$useragfind['agid'])->find();

                        // $bbsreal=BydUserSale::where('user_id',$row['userid'])->find();
//            if(!empty($des)){
                        $name=$row['username'].$row['idcart'];
//            }else{
//                $name='乙方';
//            }
                        $arrs=$agment['content'];
                        $arrs=str_replace('{$name}',$name,$arrs);
                        $content=$arrs;
                        $userag=\app\admin\model\BydUserAg::where('user_id',$row['user_id'])->update(['status'=>1,'content'=>$content]);

                    }
                    $arr=[
                        'openid'=>$user['openid'],
                        'thing1'=>"宝芸邸家居",
                        'thing2'=>"通过审核",
                        'time'=>date('Y年m月d日 H:i',time()),
                        'thing5'=>"请前往设计师端完成资料",
                    ];
                    $new=new News();
                    $news=$new->desnews($arr);
                    /**
                     *     $tmp->setValue('name', $data['name']);
                    $tmp->setValue('sf', $data['idcart']);
                    $tmp->setValue('address', $data['address']);
                    $tmp->setValue('phone', $data['mobile']);
                    $tmp->setValue('email', $data['email']);
                     */
                    $time=time();
                    $timedate=datetime(time(),'Y年m月d日');
                    $a=strtotime("+12 month",time())-86400;
                    $timedates=datetime($a,'Y年m月d日');
                    $params['startime']=$timedate;
                    $params['endtime']=$timedates;
                    $user=\app\admin\model\BydUser::find($params['user_id']);
                    $params['name'] = $params['username'];
                    //$ht=$this->word2pdf($params,$row['id'],$user['des']);
                   $myself= rand(1, 999);
                   $myselfs=\app\admin\model\BydDesigner::where('id',$row['id'])->update(['myself'=>$myself]);
                    $find=\app\admin\model\BydIdentity::where('id',$params['level'])->find();//查询身份分佣金额
                    $rand=rand(1,9999);

                    $head=$find['idenhead'];
                    $num="D-" .  str_pad(rand(1,9999), 5, '0',  STR_PAD_LEFT);
                    $bh=\app\admin\model\BydDesigner::where('id',$row['id'])->update(['bh'=>$num]);
                    $arr=[
                        'idcar'=>$params['level'],
                         'user_id' =>$params['user_id'],
                    ];
                    $level=\app\api\model\BydIdentity::dessub($arr);
                }elseif($params['state']==2){
                    $arr=[
                        'openid'=>$user['openid'],
                        'thing1'=>"宝芸邸家居",
                        'thing2'=>"审核失败",
                        'time'=>date('Y年m月d日 H:i',time()),
                        'thing5'=>"请前往平台重新完善资料",
                    ];
                    $new=new News();
                    $news=$new->desnews($arr);

                    $add=new Bydletter();
                    $add->data([
                        'user_id'=>$params['user_id'],
                        'orderid'=>0,
                        'content'=>'您的设计师申请被驳回',
                        'zt'=>$params['bhnew'],
                        'state'=>0
                    ]);
                    $add->save();
                }
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
/*
 * 生成合同
 */
    public function word2pdf($data,$id,$type)
    {
        // $com = new \COM('word.application');  （#注意word.application 是电脑中必须有word文档才可以的）

        $templet['id'] = $id;
        $server = $_SERVER['DOCUMENT_ROOT'];
        $filenamedoc = $server . '/uploads/crtoo.docx';
        //echo $filenamedoc;die;
        //$filenamedoc =$server.'/'.$templet['url'];//模板路径
        if($type==3){
            $yuanName ='/uploads/one_' . $templet['id'] . 'new.docx';
        }else{
            $yuanName ='/uploads/one_' . $templet['id'] . 'news.docx';
        }
        $filenamepdf = $server .$yuanName;//替换变量，新的word路径
        $fiel = '/uploads/one' . $templet['id'] . '_new' . time() . '.pdf';//word转换pdf路径
        $pdf = $server . $fiel;
        $tmp = new \PhpOffice\PhpWord\TemplateProcessor($filenamedoc);//打开模板
        $tmp->setValue('name', $data['name']);
        $tmp->setValue('sf', $data['idcart']);
        $tmp->setValue('address', $data['address']);
        $tmp->setValue('phone', $data['mobile']);
        $tmp->setValue('email', $data['email']);
        $tmp->setValue('startime', $data['startime']);
        $tmp->setValue('endtime', $data['endtime']);
        $tmp->saveAs($filenamepdf);//另存为
        if($type==3){
            Db::name('byd_designer')->where('id',$id)->update(['contrin'=>$yuanName]);
        }else{
            Db::name('byd_designer')->where('id',$id)->update(['contrins'=>$yuanName]);
        }

       // $url = $this->word2pdf($filenamepdf, $pdf);
        return 111;
    }

    function word2pdfs($srcfilename, $destfilename)
    {
        try {
            if (!file_exists($srcfilename)) {
                unlink($srcfilename);
            }
            $word = new \COM("word.application") or die("Can't start Word!");
            $word->Visible = 0;
            $word->Documents->Open($srcfilename, false, false, false, "1", "1", true);
            $word->ActiveDocument->final = false;
            $word->ActiveDocument->Saved = true;
            $word->ActiveDocument->ExportAsFixedFormat(
                $destfilename,
                17,                         // wdExportFormatPDF
                false,                      // open file after export
                0,                          // wdExportOptimizeForPrint
                3,                          // wdExportFromTo
                1,                          // begin page
                5000,                       // end page
                7,                          // wdExportDocumentWithMarkup
                true,                       // IncludeDocProps
                true,                       // KeepIRM
                1                           // WdExportCreateBookmarks
            );
            $word->ActiveDocument->Close();
            $word->Quit();
        } catch (\Exception $e) {
            if (method_exists($word, "Quit")) {
                $word->Quit();
            }
            return  111;
        }
    }
    /**
     * 检测是否有新退货消息
     */
    public function isHaveNewAfter()
    {
        $cache=\think\Cache::get('des');
        if(!empty($cache)){
            $tips = 'aftersale:tips:number';
            //edis = (new Redis())->getRedis();
            $tipsNumber = rand();
            $this->success('获取新设计师消息数量成功', null, $tipsNumber);
        }

    }

    /**
     * 已确认新退货消息
     */
    public function handleTui()
    {
        $type = $this->request->post('type');
        $tips = 'aftersale:tips:number';
        $tipsNumber = rand();
        \think\Cache::rm('des');
        $this->success('确认新设计师消息成功', null, $type);
    }
}
